package com.dcjt.firehotcarpad.widget

import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.view.View
import androidx.core.view.get
import androidx.recyclerview.widget.RecyclerView

/**
 * 时间轴间隔线
 * width 时间轴宽度
 * top /圆距离item顶部高度
 * goingDrawable 绿色对勾圆
 * goingDrawableSize 绿色对勾圆直径
 * dividerHeight 线条粗细
 */
class TimelineDecoration(
        private val width: Int,
        private val top: Int,
        private val goingDrawable: Drawable,
        private val goingDrawableSize: Int,
        private val dividerHeight: Int
) : RecyclerView.ItemDecoration() {
    private val ovalRadius = 12 //灰色圆的半径
    private val lintColor = -0x666667 //线条颜色

    private val mPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private var isTop = true

    override fun getItemOffsets(
            outRect: Rect,
            view: View,
            parent: RecyclerView,
            state: RecyclerView.State
    ) {
        isTop = parent.getChildLayoutPosition(view) == 0
        outRect.set(width, 0, 0, dividerHeight)
    }

    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        val childCount = parent.childCount

        for (i in 0 until childCount) {
            val child = parent.getChildAt(i)
            val top = child.top
            val bottom = child.bottom

            //竖直线
            mPaint.color = lintColor
            val left = parent.paddingLeft + width / 2
            c.drawRect(
                    left.toFloat(),
                    if (i == 0 && parent.getChildLayoutPosition(parent[i]) == 0) (this.top + goingDrawableSize).toFloat() else top.toFloat(),  //第一个item线有空一段
                    (left + dividerHeight).toFloat(),
                    (bottom + dividerHeight).toFloat(),
                    mPaint
            )

            //小圆点
            val ovalCenterX = top + this.top + ovalRadius
            // 判断当前顶部的item是不是Adapter的第一个Item
            if (i == 0 && parent.getChildLayoutPosition(parent[i]) == 0) {
                goingDrawable.setBounds(
                        left - goingDrawableSize / 2,
                        top + this.top,
                        left + goingDrawableSize / 2,
                        top + this.top + goingDrawableSize
                )
                goingDrawable.draw(c)
            } else {
                c.drawCircle(left.toFloat(), ovalCenterX.toFloat(), ovalRadius.toFloat(), mPaint)
            }
        }


    }

}